﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;

namespace HelpInfo.GetMsWeb.WebApi.ConsoleApplicationClient
{
    class Program
    {

        public class Agent
        {
            public string Nom { get; set; }
            public string Prénom { get; set; }
            public string Matricule { get; set; }
        }


        static void Main(string[] args)
        {
            IEnumerable<Agent> agents = GetAgents(); 
            PrintAgents(agents);
            Console.ReadLine();
        }

        private static IEnumerable<Agent> GetAgents()
        {
            IEnumerable<Agent> agents = null;
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(ConfigurationManager.AppSettings["adressWebApiServer"].ToString());

            // Add an Accept header for JSON format.
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));
            // List all agents.
            HttpResponseMessage response = client.GetAsync("api/Agent").Result;  // Blocking call!
            if (response.IsSuccessStatusCode)
            {
                try
                {
                    agents = response.Content.ReadAsAsync<IEnumerable<Agent>>().Result;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            else
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }
            return agents;
        }


        private static void PrintAgents(IEnumerable<Agent> agents)
        {
            foreach (Agent item in agents)
            {
                Console.Write("Nom={0} Prénom={1} Matricule={2}\r\n\r\n",
                     item.Nom, item.Prénom, item.Matricule);       
            }
        }
    }
}
